/*
 *  Filename:      hal_board.c
 *  Author:         Erick Huang<erickhuang1989@gmail.com>
 *  Revised:        2014-12-16
 *  Description:   
 *
 *  Copyright (c) Erick Huang. All rights reserved.
 */
#include "meos_api.h"
#include "hal_drivers.h"
#include "hal_key.h"

// Registered keys task ID, initialized to NOT USED.
static uint8 registeredKeysTaskID = TASK_NO_TASK;


/*********************************************************************
 * @fn      OnBoard_Init()
 * @brief   Initialize the Board Peripherals
 * @param   level: COLD,WARM,READY
 * @return  None
 */
void OnBoard_Init( uint8 level )
{
  	if ( level == OB_COLD )
  	{
    	// Interrupts off
    	HAL_DISABLE_INTERRUPTS();
  	}
  	else if ( level == OB_WARM)
  	{
  		
  	}
	else  //OB_READY
  	{
    	HalKeyConfig( HAL_KEY_INTERRUPT_ENABLE, OnBoard_KeyCallback );
  	}
}

/*********************************************************************
 *  @fn       RegisterForKeys()
 *  @brief   If a task registers, it will get all the keys. 
 */
Status_t RegisterForKeys( uint8 task_id )
{
  	// Allow only the first task
  	if ( registeredKeysTaskID == TASK_NO_TASK )
  	{
    	registeredKeysTaskID = task_id;
    	return SUCCESS;
  	}
  	else
    	return FAILURE;
}

/*********************************************************************
 *  @fn       OnBoard_KeyCallback()
 *  @brief   Callback service for keys. It will Send "Key Pressed" message to application. 
 */
Status_t OnBoard_KeyCallback( uint8 keys, uint8 state )
{
  	keyChange_t *msgPtr;

  	if ( registeredKeysTaskID != TASK_NO_TASK )
  	{
    	// Send the address to the task
    	msgPtr = (keyChange_t *)meos_msg_allocate( sizeof(keyChange_t) );
    	if ( msgPtr )
    	{
      		msgPtr->hdr.type = MSG_TYPE_KEY_CHANGE;
      		msgPtr->state = state;
      		msgPtr->keys = keys;

      		meos_msg_send( registeredKeysTaskID, (uint8 *)msgPtr );
    	}
    	return SUCCESS;
  	}
  	else
    	return FAILURE;
}


